/*
 *管道特性：
 * 	1，上下管道成对出现，x轴坐标可以共享
 *  2，上下管道之间的间距是固定的，右用户指定
 *  3，管道高度随机生成
 *  4，当一对管道走出画布时，从右边出来时的高度再次随机生成
 *  5，需要指定管道的最小高度和最大高度
 * 
 * 
 * */
(function(window) {
	/*
	 *参数：
	 * 1，ctx
	 * 2,img:imgDown,imgUp
	 * 3,管道最大高度，最低高度
	 * 4，左右间隔
	 * 
	 * 
	 * 
	 * */
	loadPipe.len = 0;

	function loadPipe(options) {
		loadPipe.len++;
		this.ctx = options.ctx;
		this.imgDown = options.imgDown;
		this.imgUp = options.imgUp;

		//管道在画布上的最小高度和最大高度
		this.minHeight = options.minHeight;
		this.maxHeight = options.maxHeight;

		//左右间距
		this.pipeLRspace = options.pipeLRspace || 200;

		//上下距离
		this.pipeTBspace = options.pipeTBspace || 150;

		//		//管道的宽高
		//		this.width = this.imgDown.width;
		//		this.height = 0;

		//管道图像的宽高
		this.imgHeight = this.imgDown.height;
		this.imgWidth = this.imgDown.width;

		//管道的坐标
		this.x = 300 + (this.imgWidth + this.pipeLRspace) * (loadPipe.len - 1);
		//		this.x=300;
		this.y = 0;

		//管道每秒运行的速度
		this.speed = 150;

		//管道每秒的加速度
		this.a = 2;
		this.computePipeY();

	}

	//置换原型
	loadPipe.prototype = {
		constructor: loadPipe,
		//计算管道y轴坐标
		computePipeY: function() {
			var pipeUpViewHeight = util.random(this.minHeight, this.maxHeight);
			//上管道的y轴坐标
			this.downY = pipeUpViewHeight - this.imgHeight;

			//下管道的y轴坐标
			this.upY = pipeUpViewHeight + this.pipeTBspace;
		},
		//绘制管道
		draw: function() {
			this.ctx.drawImage(this.imgDown, this.x, this.downY);
			this.ctx.drawImage(this.imgUp, this.x, this.upY);
			this.drawPath();
		},
		//更新下一次管道绘制时的数据
		update: function(delaySecond) {

			//this.x -= delaySecond * this.speed;//匀速时每次更新后，x轴的坐标

			//给管道一个加速度 每次移动的距离s=vt+at^2/2
			this.x -= this.speed * delaySecond + this.a * delaySecond * delaySecond / 2;
			//更新速度
			this.speed = this.speed + this.a * delaySecond;

			if(this.x <= -this.imgWidth) {
				this.x += (this.imgWidth + this.pipeLRspace) * loadPipe.len;
				this.computePipeY(); //再次生成随机数
			}
		},
		/*
		 * function 根据管道的宽度以及坐标绘制相应的矩形路径
		 * param { drawCtx: Object } 绘制上下文
		 * */
		drawPath: function() {
			this.ctx.rect(this.x, this.downY, this.imgWidth, this.imgHeight);
			this.ctx.rect(this.x, this.upY, this.imgWidth, this.imgHeight);
			//this.ctx.stroke();
		}
	}
	window.loadPipe = loadPipe;
}(window))